package com.goscom.app.deeset;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import com.goscom.app.database.DBAdapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager.LayoutParams;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class ContractualAgreement extends Activity {

	private String strMerId = "";
	private DBAdapter mDB;
	private File myPath;
	private String strPath = "";
	private com.goscom.app.deeset.DrawSomethingView drView;
	private RelativeLayout rltMainLayout;
	private ImageView imgSign;
	private LinearLayout layout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contractual);
		imgSign = (ImageView) findViewById(R.id.imgContractualSign);
		mDB = new DBAdapter(ContractualAgreement.this);
		mDB.open();

		getMerId();
	}

	public void getMerId() {
		strMerId = getIntent().getStringExtra("merid");
		ContentValues content = new ContentValues();
		content = mDB.queryDataByMerId("CONTRACTUAL", strMerId);
		if (content != null && content.getAsByteArray("sign") != null ) {
			imgSign.setImageBitmap(BitmapFactory.decodeByteArray(
					content.getAsByteArray("sign"), 0,
					content.getAsByteArray("sign").length));
			imgSign.setVisibility(View.VISIBLE);
		}

	}

	public void clearSign(View v) {
		imgSign.setImageDrawable(null);
		strPath = "";
		if (mDB.queryMerchandiser("CONTRACTUAL", strMerId) != 0) {
			File file = new File("/mnt/sdcard/DCMI/" + strMerId + "-signature.png");
			if (file.exists()) {
				file.delete();
			}
			mDB.deleteData("CONTRACTUAL", strMerId);
		}
	}

	public void goPrevious(View v) {
		if (mDB != null) {
			mDB.close();
		}
		onBackPressed();
	}

	public void sendEmail(View v) {
		startActivity(new Intent(this, UploadData.class).putExtra("merid", strMerId));
	}

	public void agreeSign(View v) {
		saveDB();
		if (strPath.equals("")) {
			Toast.makeText(this, "Clear signature!!!", Toast.LENGTH_SHORT)
					.show();
		} else {
			Toast.makeText(this, "Save signature!!!", Toast.LENGTH_SHORT)
					.show();
		}
	}

	public void Logout(View v) {
		if (mDB != null) {
			mDB.close();
		}
		startActivity(new Intent(ContractualAgreement.this, Login.class));
	}

	public void signAgreement(View v) {
		final AlertDialog builder = new AlertDialog.Builder(
				ContractualAgreement.this).create();

		// tieu de dialog
		builder.getWindow();
		builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
		builder.setCanceledOnTouchOutside(false);

		drView = new DrawSomethingView(ContractualAgreement.this);

		// tao layout chua cac view title va description
		layout = new LinearLayout(ContractualAgreement.this);

		LayoutParams params = new LayoutParams();
		params.width = LayoutParams.MATCH_PARENT;
		params.height = 200;

		drView.setLayoutParams(params);
		layout.addView(drView);
		layout.setBackgroundColor(Color.WHITE);

		// dua layout vao dialog
		builder.setView(layout);

		// khi chon OK
		builder.setButton(AlertDialog.BUTTON_POSITIVE, "Ok",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						getScreen();
						imgSign.setImageDrawable(null);
						imgSign.setImageURI(Uri.parse(strPath));
					}
				});

		// khi chon Edit, goi den activity add/edit voi tham so idtask dinh kem
		builder.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						builder.dismiss();
					}
				});
		builder.show();
	}

	private void getScreen() {

		View ve = layout;
		ve.setDrawingCacheEnabled(true);
		Bitmap b = ve.getDrawingCache();

		String extr = Environment.getExternalStorageDirectory().toString()
				+ "/DCMI";
		myPath = new File(extr);

		if (!myPath.exists()) {
			boolean result = myPath.mkdir();
		}

		// myPath = new File(extr, getString(R.string.app_name) + ".jpg");
		myPath = new File(extr, strMerId + "-signature.png");

		FileOutputStream fos = null;

		try {
			fos = new FileOutputStream(myPath);
			b.compress(Bitmap.CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
			strPath = myPath.getPath();
			Log.i("path", strPath);
		}

		catch (FileNotFoundException e) {

			Log.e("Error", e + "");
		}

		catch (Exception e) {

			Log.e("Error", e + "");
		}
	}

	public void saveDB() {
		if (mDB.queryMerchandiser("CONTRACTUAL", strMerId) == 0) {
			insertDB();
		} else {
			mDB.deleteData("CONTRACTUAL", strMerId);
			insertDB();
		}
	}

	public void insertDB() {
		ContentValues content = new ContentValues();
		content.put("merid", strMerId);
		content.put("sign", convertToByte());
		content.put("upload", "0");
		mDB.insertData("CONTRACTUAL", content);
	}

	public byte[] convertToByte() {
		byte[] image = null;
		if (strPath.equals("") == false) {
			FileInputStream fileInStream;
			try {
				fileInStream = new FileInputStream(strPath);
				BufferedInputStream bufInStream = new BufferedInputStream(
						fileInStream);
				image = new byte[bufInStream.available()];
				bufInStream.read(image);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return image;
	}

	@Override
	protected void onRestart() {
		mDB.open();
		super.onRestart();
	}

	@Override
	protected void onDestroy() {
		if (mDB != null) {
			mDB.close();
		}
		super.onDestroy();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			backupToExternal();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void backupToExternal() {
		// backup db from internal to external
		try {
			File sd = Environment.getExternalStorageDirectory();
			File data = Environment.getDataDirectory();

			if (sd.canWrite()) {
				String currentDBPath = "//data//com.goscom.app.deeset//databases//deeset";
				String backupDBPath = "deeset";
				File currentDB = new File(data, currentDBPath);
				File backupDB = new File(sd, backupDBPath);

				if (currentDB.exists()) {
					FileChannel src = new FileInputStream(currentDB)
							.getChannel();
					FileChannel dst = new FileOutputStream(backupDB)
							.getChannel();
					dst.transferFrom(src, 0, src.size());
					src.close();
					dst.close();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
